import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

/**
 * Class performs reading data
 * from SiLabs c8051f310 by
 * COM port
 * @author Hrybanov Ihor 2014
 * @version 1.0
 */
public class SiLabsValuesReader extends Thread {
    private boolean isStopped;
    private InputStream in = null;
    private Vector messageCenters = new Vector();
    public SiLabsValuesReader() {
        this.setDaemon(true);

    }

    public void run() {
        CommPortIdentifier portID = null;
        SerialPort sp = null;

        try {
            portID = CommPortIdentifier.getPortIdentifier("serial4");
            sp = (SerialPort)portID.open("outport",0);
            //Set serial port to 115200,N,8,1
            sp.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,	SerialPort.PARITY_NONE);
            //get input stream from serial port
            in = sp.getInputStream();


            while (!isStopped) {
                String temperature = "";
                if ((temperature = readData()).length() > 0) {
                    if (messageCenters.size() > 0) {
                        for  (int i = 0; i < messageCenters.size(); i++) {
                            MessageCenter messageCenter = (MessageCenter) messageCenters.elementAt(i);
                            if (messageCenter.isDestroyed()) {
                                messageCenters.removeElementAt(i);
                            } else {
                                messageCenter.setMessageToSend(temperature);
                                if (temperature.equals(messageCenter.getReceivedMessage())) {
                                    System.out.println("Message {" +
                                                        temperature + "} sent to: " +
                                                        messageCenter.getClientIdentificator());
                                    messageCenter.clearMessageToSend();
                                    messageCenter.clearReceivedMessage();
                                }
                            }
                        }
                    }
                }
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            stopThread();
            sp.close();
            e.printStackTrace();
        }

    }

    /**
    * Method initialize COM
    * and read data from it
    */
    public String readData() throws IOException {
        String message = "";

            //get value of measurement
             if (in.available() > 0) {
                 message = getData(in);
             }
            //make toggle up (wait till data will be written)

        //write data in file
        return message;
    }

    /**
    * Method read from
    * input stream and returns
    * double value of data
    *
    * @param inputStream
    * @return data
    * @throws Exception
    */
    private String getData(InputStream inputStream) throws IOException {
        //byte array to contain data from serial port
        byte[] chars = new byte[32 * 1024];
        //contains number of bytes received from serial port
        int num_chars = 0;
        //contains data received, converted to string
        String input = "";
        //loop endlessly
        while (true) {
            //readWriteData serial data into chars, length into num_chars
            num_chars = inputStream.read(chars);
            if (num_chars > 0) {
                //convert to String
                input = new String(chars, 0, num_chars);
                System.out.println(input);
                return input;
            }
        }
    }

    public boolean isStopped() {
        return isStopped;
    }

    public void stopThread() {
        isStopped = true;
    }

    public void addMessageCenter(MessageCenter messageCenter) {
        this.messageCenters.addElement(messageCenter);
    }
}

